<html>
<head>
	<title>nTube</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<style type="text/css" id="__ntheming_global">
	html {
		background-color: black;
		color: white;
	}
	</style>
	<style type="text/css" id="__ntheming_global_font">
	html {
		font-family: sans-serif;
		font-size: small;
	}
	</style>
	<style>
	h1 {
		font-family: inherit;
		font-size: small;
	}
	.h1_large {
		font-family: inherit;
		font-size: large;
	}
	</style>
	<script type="text/javascript" >
	
	function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
	}

	function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    var val = value;
    if (value == null) {
		val = "null";    
    }else if (typeof value != "string") {
		val = value.toString();    
    }
    document.cookie = name + "=" + (val || "")  + expires + "; path=/";
	}
	
	function canStoreData() {
		return typeof Storage == "function" || navigator.cookieEnabled;
	}

	function readSettings() {
		if (!canStoreData()) {
			return null;	
		}
		if (localStorage.getItem("_ntube_settings") != null) {
			return localStorage.getItem("_ntube_settings");
		}else {
			return getCookie("settings");
		}	
}

	function readSettingsToJSON() {
		var rs = readSettings();
		if (rs == null) {
			return null;	
		}
		return JSON.parse(b64DecodeUnicode(rs));
	}
	
	function applyTheme(themeCode) {
		console.log("[nTube: nTheming] Loading CSS for this page...");
		send_request("/api/get_css?eurl=" + themeCode, "", function () {
			console.error("[nTube: nTheming] Failed to load CSS!");
		}, function (data) {
			document.getElementById("__ntheming_global").innerHTML = data;
		});
	}
	
	function applyFont(fontCode) {
		console.log("[nTube: nTheming] Loading font for this page...");
		send_request("/api/get_font?eurl=" + fontCode + "&ovr=small", "", function () {
			console.error("[nTube: nTheming] Failed to load font!");
		}, function (data) {
			document.getElementById("__ntheming_global_font").innerHTML = data;
		});
	}
	
	function b64DecodeUnicode(str) {
    try {
 		return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
        	return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    	}).join(''));   	
    }catch (ex) {
    	return atob(str);	
    }
	}

	function b64EncodeUnicode(str) {
    try {
 		return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode(parseInt(p1, 16))
    	}));
 	 }catch (ex) {
 	 	return btoa(str);
	 }
	}

	function writeSettingsFromJSON(jsonObject) {
		var enc = b64EncodeUnicode(JSON.stringify(jsonObject));
		setCookie("settings", enc, 9007199254740991);
		if (typeof Storage == "function") {
			localStorage.setItem("_ntube_settings", enc);	
		}
	}
	
	function numberWithCommas(n) {
    	var parts=n.toString().split(".");
    	return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
	}
	
	function loadChannel() {
		window.subscribed = false;
		var settings = readSettingsToJSON();
		if (settings != null && settings.theme) {
			applyTheme(settings.theme);		
		}
		if (settings != null && settings.font) {
			applyFont(settings.font);		
		}
		var stop = false;
		if (typeof fetch == "undefined") {
			stop = true;
			document.getElementById("__no_fetch_warn").style.display = "";
			document.getElementById("__no_fetch_warn").style.visibility = "";
			document.getElementById("__no_fetch_warn").style.color = "orange";
		}
		if (stop) {
			return;			
		}
		String.prototype.replaceAll = function(searchStr, replaceStr) {
				var str = this;

    			// no match exists in string?
    			if(str.indexOf(searchStr) === -1) {
        			// return string
        			return str;
    			}

    			// replace and remove first match, and do another recursirve search/replace
    			return (str.replace(searchStr, replaceStr)).replaceAll(searchStr, replaceStr);
		}
		Array.prototype.remByVal = function(val) {
    		for (var i = 0; i < this.length; i++) {
        		if (this[i] === val) {
            		this.splice(i, 1);
            		i--;
        		}
    		}
    		return this;
		}
		var URL = document.URL;
		try {
			var vidID = URL.split("\?")[1];
			send_request("channel_api?" + vidID, "", function() {
				alert("Failed to get channel, an error occured.");
			}, function(data) {
				try{
					var jsonObject = JSON.parse(data);
					document.title = jsonObject.cName + " - nTube";
					document.getElementById("_channel_name").innerHTML = jsonObject.cName;
					document.getElementById("_sub_cname").innerHTML = jsonObject.cName;

					window.Channel = {
						"lastVid": jsonObject.lastVid,
						"image": jsonObject.images.channel,
						"cName": jsonObject.cName,
						"cid": jsonObject.channelID,
					};
					Object.freeze(window.Channel);
					document.getElementById("_sub_button").disabled = false;
					
					if (jsonObject.familyFriendly) {
						document.getElementById("_channel_ff").style.opacity = "1.0";
					}
					if (jsonObject.paidContent) {
						document.getElementById("_channel_pc").style.opacity = "1.0";
					}
					//document.getElementById("_channel_ff").innerHTML = "Family friendly channel &#129300; : " + jsonObject.familyFriendly;
					//document.getElementById("_channel_pc").innerHTML = "Paid content present: " + jsonObject.paidContent;
					if (jsonObject.images) {
						document.getElementById("__channel_ban").src = jsonObject.images.qualityBanner;
						document.getElementById("__channel_ban1").src = jsonObject.images.channel;
					}
					if (jsonObject.subscribers) {
						document.getElementById("_sub_count").innerHTML = numberWithCommas(jsonObject.subscribers);
					}			
					var arr = jsonObject.videos;
					var i = 0;
					var videos = document.getElementById("_videos");
					for (; i < arr.length; i++) {
						var x = arr[i];
						var vT = document.createElement("p");
						vT.innerHTML = x.title;
						var vU = document.createElement("a");
						vU.href = x.url;
						vU.innerHTML = "<img src=\"" + x.thumb + "\" alt=\"\"></img>";
						videos.appendChild(vT);
						videos.appendChild(vU);
					}
					if (settings.subscriptions) {
						var dataCorrected = false;
						for (var i = 0; i < settings.subscriptions.length; i++) {
							var item = settings.subscriptions[i];
							if (item == undefined) {
								continue;
							}
							if (item == null) {
								settings.subscriptions = settings.subscriptions.remByVal(null);
								dataCorrected = true;
								continue;
							}
							if (item.cid == jsonObject.channelID) {
								document.getElementById("_sub_status").innerHTML = "";
								window.subscribed = true;
								break;
							}
						}
						if (dataCorrected) {
							writeSettingsFromJSON(dataCorrected);
						}
						if (window.subscribed) {
							document.getElementById("_sub_start").innerHTML = "Unsubscribe";
						}else {
							document.getElementById("_sub_start").innerHTML = "Subscribe";
						}
					}
				}catch (ex) {
					console.error(ex);
					alert("Failed to get channel data while parsing.");
				}
			});
			document.getElementById("_channel_name").innerHTML = "Loading...";	
		}catch (ex) {
			console.error(ex);
			alert("Failed to get channel data!");
		}
	}	
	
	function send_request(url, data, onFail, onSuccess) {
	if (typeof fetch != "undefined") {
		fetch(url).then(function(response) {
    		return response.text();
   	}).then(function(json) {
   		onSuccess(json);
   	}).catch(function(ex) {
   		console.error(ex);
    		onFail();
  		});	
	}else {
		console.warn("send_request() -> Outdated browser found, attempting fallback method...");
		var http = new XMLHttpRequest();
		http.open('POST', url, true);
	   http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	   
	   var hasResponse = false;
	   //var res = "";
	   http.onreadystatechange = function() {
		if (http.readyState == 4 && http.status == 200) {
		//		res = http.responseText;
				onSuccess(http.responseText.split("\n")[4]);
			}
		}
		http.ontimeout = function() {
			alert("nTube: onTimeout() was called when fetching your video!");
		}
		http.send(params);
	}
	//var http = new XMLHttpRequest();
	//var params = data;
	//http.timeout = 0;
	//http.responseType = 'blob';
	//http.open('POST', url, true);
	//http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			
	//var hasResponse = false;
	//var res = "";
	//http.onreadystatechange = function() {
	//	if (http.readyState == 4 && http.status == 200) {
	//		res = http.responseText;
	//		onSuccess(http.responseText);
	//	}
	//}
	//http.ontimeout = function() {
	//	alert("nTube: onTimeout() was called when fetching your video!");
	//}
	//http.send(params);
	
	/*		
	var stop = false;
	var time = 0;
	while (!hasResponse) {
		if (stop) {
			break;
		}
		if (time > 1500) {
			//alert("Timeout occured, try again.");
			onFail();
			stop = true;
		}
		var ix = -1;
		time += 1;
	}*/
}
	</script>
	<div style="width: 100%;border-bottom: 1px solid green;">
	<a href="/" style="text-decoration: none;color: inherit;"><h1 style="display: inline-block;">&nbsp;<span style="color: red;">n</span><span style="color: lightgreen;">Tube</span></h1></a>
	<p style="float: right;">version 1.5-legacy</p>
	<h1 id="__no_fetch_warn" style="visibility: hidden;display: none;">fetch() is missing, nTube may not function on your browser.</h1>
	</div>
	<div style="width: 100%; border-bottom: 1px solid green;">
		<img src="" alt="$channel.banner" style="width: 100%;height: 15%;" id="__channel_ban"></img>
	</div>
	<div style="width: 100%; border-bottom: 1px solid green; height: 24px;">
		<div>
			<div style="display: inline-block;">
				<div style="border-left: 1px solid green; border-right: 1px solid green;display: inline-table;">
					<img title="Status of the channel being family friendly. (Grayed out meaning the channel is NSFW)" id="_channel_ff"src="/resources/family_small.png" alt="$image.friendlyChannel" style="opacity: 0.6;display: inline;width: 24px; height: 24px;vertical-align: middle;">	
				</div>	
				<div style="border-left: 1px solid green; border-right: 1px solid green;display: inline-table;">
					<img title="Status of paid content on the channel. (Grayed out means there is no paid content)" id="_channel_pc" src="/resources/money_small.png" alt="$image.paidContent" style="opacity: 0.6;display: inline;width: 24px; height: 24px;vertical-align: middle;">		
				</div>			
			</div>		
			<div style="display: inline-block;vertical-align: middle;float: right;">
				<p style="vertical-align: middle;line-height: 70%;"><span id="_sub_count">-1</span> subscribers</p>			
			</div>
		</div>
	</div>
	<div>
		<div>
				<center style="padding-left: 70px;">
					<img src="" alt="$channel.image" style="width: 32px; height: 32px;display: inline;vertical-align: middle;" id="__channel_ban1">
					<h1 class="h1_large" id="_channel_name" style="display: inline;vertical-align: middle;">$channel.name</h1>		
				</center>			
		</div>
	</div>
	<!--
	<h3 id="_channel_ff">Family friendly channel &#129300; : false</h3>
	<h3 id="_channel_pc">Paid content present: false</h3>-->
</head>
<body onload="loadChannel();">
	<div style="width: 100%;">
		<div style="border: 1px solid green;display: inline-table;width: 74%;height: 20%;">
			<h2 style="text-align: center;">About</h2>
			<p style="text-align: center;color: gray;">Coming soon...</p>		
		</div>
		<div style="border: 1px solid green;display: inline-table;width: 25%;height: 20%;">
			<center>
				<h2>Your Subscription</h2>
				<p style="font-size: small;">You are currently <span id="_sub_status">NOT </span>subscribed.</p>
				<button style="background-color: inherit; color: green;border: 1px solid green;" onclick="; _subscribe(); return false;" disabled="true" id="_sub_button">
						<span id="_sub_start">Subscribe</span> to <span id="_sub_cname">$name</span>
				</button>
				<p style="font-size: x-small;color: red;">Cookies and/or Local Storage is required.</p>
				<script>
				var remByCID = function(arr, val) {
    				for (var i = 0; i < arr.length; i++) {
        				if (arr[i].cid === val) {
            				arr.splice(i, 1);
            				i--;
        				}
    				}
    				return arr;
				};

				function _subscribe() {
					if (!window.Channel) {
						alert("window.Channel is missing, bailing out...");
						return;
					}
					var settings = readSettingsToJSON();
					if (window.subscribed) {
						var s = false;
						for (var i = 0; i < settings.subscriptions.length; i++) {
							var item = settings.subscriptions[i];
							if (item == undefined) {
								continue;
							}
							if (item == null || item.cid == null) {
								//delete settings.subscriptions[i];
								//delete item;
								/*if (settings.subscriptions.length == 1) {
									settings.subscriptions = settings.subscriptions.splice(i, 0);
								}else {
									settings.subscriptions = settings.subscriptions.splice(i + 1, 1);
								}*/
								settings.subscriptions = settings.subscriptions.remByVal(null);
								continue;
							}
							if (item.cid == window.Channel.cid) {
								s = true;
								window.subscribed = false;
								//delete settings.subscriptions[i];
								//delete item;
								//if (settings.subscriptions.length == 1) {
								//	settings.subscriptions = settings.subscriptions.splice(i, 0);
								//}else {
								//	settings.subscriptions = settings.subscriptions.splice(i + 1, 1);
								//}
								settings.subscriptions = remByCID(settings.subscriptions, window.Channel.cid);
								break;
							}
						}
						if (s) {
							document.getElementById("_sub_status").innerHTML = "NOT ";
							alert("You have unsubscribed from " + window.Channel.cName + ".");
							document.getElementById("_sub_start").innerHTML = "Subscribe";
						}else {
							alert("Couldn't unsubscribe to " + window.Channel.cName + ".");
						}
					}else {
						var l = settings.subscriptions.length;
						settings.subscriptions[l] = JSON.parse(JSON.stringify(window.Channel));
						alert("You have subscribed to " + window.Channel.cName + ".");
						document.getElementById("_sub_status").innerHTML = "";
						window.subscribed = true;
						document.getElementById("_sub_start").innerHTML = "Unsubscribe";
					}
					writeSettingsFromJSON(settings);
				}
				</script>
			</center>
		</div>
	</div>
	<h2>Videos</h2>
	<div id="_videos"></div>
</body>
</html>
